package com.example.jdbc.demo.base;


import com.example.jdbc.demo.utils.Page;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

import java.util.List;

@Scope("prototype")
@Component
public class BaseJdbcDao {

    private final Log logger = LogFactory.getLog(BaseJdbcDao.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private NamedParameterJdbcTemplate nameJdbcTemplate;

    /**
     * @功能描述:分页
     */
    public <T> Page<T> queryPage(String sql, BaseSqlCondition cond, Class<T> clazz) {
        String countSQL = "SELECT count(1) FROM (" + sql + ") t";
        int rowCount = jdbcTemplate.queryForObject(countSQL, cond.getArray(), Integer.class);
        int pageSize = cond.getSize();
        int curPage = cond.getPage();
        int pageCount = rowCount % pageSize == 0 ? rowCount / pageSize : rowCount / pageSize + 1;
        String listSql = sql + " LIMIT " + curPage * pageSize + "," + pageSize;
        List<T> dataList = jdbcTemplate.query(listSql.toString(), cond.getArray(), new BeanPropertyRowMapper<T>(clazz));
        return new Page<T>(dataList, cond.getPage(), rowCount, cond.getSize(), pageCount);
    }

    /**
     * @功能描述:批操作
     */
    public <T> int[] batchOperate(List<T> list, String sql) {
        SqlParameterSource[] params = new SqlParameterSource[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = new BeanPropertySqlParameterSource(list.get(i));
        }
        return nameJdbcTemplate.batchUpdate(sql, params);
    }

    /**
     * @功能描述:插入记录反加主键
     */
    public <T> long saveKey(T t, String sql, String id) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        SqlParameterSource params = new BeanPropertySqlParameterSource(t);
        nameJdbcTemplate.update(sql, params, keyHolder, new String[] { id });
        return keyHolder.getKey().longValue();
    }
}
